/*
 * City 控制器
 * @Author: chiangbt@geoportal.cn 
 * @Date: 2019-05-07 11:25:03 
 * @Last Modified by: chiangbt@geoportal.cn
 * @Last Modified time: 2019-05-10 11:08:35
 */
const mongoose = require('mongoose');
const City = require('../models/city');

/**
 * 获取city数据
 */
exports.city_get_all = (req, res, next) => {
    const limit = parseInt(req.query.limit) || 15
    const offset = parseInt(req.query.offset) || 0

    City.count({}, function (err, counts) {
        City.find().skip(offset).limit(limit) // 一次返回默认的15条记录
            .sort({
                '_id': -1
            })
            .select('_id name geometry createdAt') // 限制返回字段
            .then(cities => {
                // 返回cities的同时，对返回结果进行构造
                return res.status(200).json({
                    type: "FeatureCollection",
                    featureCount: counts,
                    features: cities.map(city => {
                        return {
                            type: "Feature",
                            properties: {
                                id: city._id,
                                name: city.name,
                                createdAt: city.createdAt
                            },
                            geometry: city.geometry
                        }
                    })
                });
            })
            .catch(err => {
                return res.status(500).json({
                    success: false,
                    error: err.message
                });
            });
    });
}

/**
 * 添加新city
 */
exports.create_city = (req, res, next) => {
    // 在本处代码中不需要进行name验证式查询
    // Model中的unique插件验证保证了重复name会返回异常结果
    const city = new City({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        geometry: req.body.geometry
    });

    city.save().then(city => {
        return res.status(201).send({
            success: true,
            message: '创建 city 对象成功.',
            feature: {
                type: "Feature",
                properties: {
                    id: city._id,
                    name: city.name,
                    createdAt: city.createdAt
                },
                geometry: city.geometry
            }
        })
    }).catch(err => {
        return res.status(500).json({
            success: false,
            error: err.message
        });
    });
}

/**
 * 获取指定city
 */
exports.city_get_by_id = (req, res, next) => {
    const id = req.params.id;

    City.findById({
            _id: id
        })
        .select('_id name geometry createdAt')
        .then(city => {
            if (city) {
                return res.status(200).json({
                    success: true,
                    message: '获取 city 对象成功.',
                    feature: {
                        type: "Feature",
                        properties: {
                            id: city._id,
                            name: city.name,
                            createdAt: city.createdAt
                        },
                        geometry: city.geometry
                    }
                });
            } else {
                return res.status(404).json({
                    success: false,
                    message: "No valid entry found for provided ID"
                });
            }
        })
        .catch(err => {
            return res.status(500).json({
                success: false,
                error: err.message
            });
        });
}

/**
 * 删除指定的City
 */
exports.delete_city = (req, res, next) => {
    City.findOneAndRemove({
            _id: req.params.id
        })
        .then(result => {
            if (result) {
                return res.status(200).json({
                    success: true,
                    message: "City deleted"
                });
            } else {
                return res.status(400).json({
                    success: false,
                    error: 'City 不存在'
                });
            }
        })
        .catch(err => {
            return res.status(500).json({
                success: false,
                error: err.message
            });
        });
}

/**
 * 更新指定city
 */
exports.update_city = (req, res, next) => {
    const id = req.params.id;
    const city = req.body;
    const {
        ...updateData
    } = city

    City.findByIdAndUpdate({
            _id: id
        }, updateData, {
            new: true
        })
        .select('_id name geometry createdAt')
        .then(city => {
            if (city) {
                return res.status(200).json({
                    success: true,
                    message: '更新 city 对象成功.',
                    feature: {
                        type: "Feature",
                        properties: {
                            id: city._id,
                            name: city.name,
                            createdAt: city.createdAt
                        },
                        geometry: city.geometry
                    }
                });
            } else {
                return res.status(400).json({
                    success: false,
                    error: '更新的city并不存在'
                });
            }
        })
        .catch(err => {
            return res.status(500).json({
                success: false,
                error: err.message
            });
        });
}

/**
 * 空间查询
 * 非标准Restful服务，参数由query提供
 */
exports.city_search_near = (req, res, next) => {
    const lat = req.query.lat;
    const lng = req.query.lng;
    const distance = req.query.distance;

    City.find({
            geometry: {
                $near: {
                    $maxDistance: distance,
                    $geometry: {
                        type: "Point",
                        coordinates: [lng, lat]
                    }
                }
            }
        })
        .then(cities => {
            if (cities) {
                return res.status(200).json({
                    type: "FeatureCollection",
                    features: cities.map(city => {
                        return {
                            type: "Feature",
                            properties: {
                                id: city._id,
                                name: city.name,
                                createdAt: city.createdAt
                            },
                            geometry: city.geometry
                        }
                    })
                });
            } else {
                return res.status(404).json({
                    success: false,
                    message: "No valid entry found for provided ID"
                });
            }
        })
        .catch(err => {
            return res.status(500).json({
                success: false,
                error: err.message
            });
        });
}